const { getSqlLiteData } = require('../../../SqlLiteDB');
const pathLib = require('path');
const fs = require('fs');

module.exports = function setDeleteFileRouter (router) {

    //删除文件
    router.post('/deleteFiles', async function (req, res, next) {
        try {
            // 要删除的文件在req.files中
            let dataContent = JSON.parse(req.body['dataContent']);
            let files = dataContent.files;
            let deleteResultArr = [];
            for (let i = 0; i < files.length; i++) {
                // const filename = files[i].path + pathLib.parse(files[i].originalname).ext;
                // console.log(filename);
                let isFilePath = fs.statSync('.' + files[i].filePath).isFile();

                let deleteResult = '';
                if (isFilePath) {
                    deleteResult = await deleteFile(files[i]);
                }
                else {
                    deleteResult = await deleteFolderRecursive('.' + files[i].filePath);
                }
                deleteResultArr.push(deleteResult);
            }
            res.status(200).json({
                result: deleteResultArr,
            });
        }
        catch (ex) {
            res.status(500).json({
                result: ex,
            });
            console.log('ex :>> ', {
                result: ex,
            });
        }
    });

    let deleteFile = function (file) {
        return new Promise((resolve, reject) => {

            fs.unlink(`.${file.filePath}`, (err) => {
                if (err) {
                    if (err.code == 'ENOENT') {
                        resolve('文件本来就不存在,文件删除成功');
                    }
                    else {
                        resolve(err);
                    }
                }
                else {
                    resolve('文件删除成功');
                }
            });

        });
    };
    let deleteFolderRecursive = function (path) {
        return new Promise((resolve, reject) => {
            if (fs.existsSync(path)) {
                fs.readdirSync(path).forEach(function (file) {
                    var curPath = path + "/" + file;
                    if (fs.statSync(curPath).isDirectory()) { // recurse
                        deleteFolderRecursive(curPath);
                    } else { // delete file
                        fs.unlinkSync(curPath);
                    }
                });
                fs.rmdirSync(path);
                resolve('文件删除成功');
            }
            else {
                resolve('文件本来就不存在,文件删除成功');
            }
        });
    };
};
